package com.ficv.findme;

import java.util.Date;

import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.DroidGap;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;


public class MainActivity extends DroidGap {
	
public static final String EXTRA_MESSAGE = "hayMsg";



//		public static String URL_BASE="http://192.168.2.188:8181/tucanalmovil/devices/";
	//public static String URL_BASE="http://172.16.14.3:8181/tucanalmovil/devices/";
	public static String URL_BASE="https://findme2.cfapps.io/devices/";
//	public static String URL_BASE="http://192.168.2.113:8181/tucanalmovil/devices/";
//	public static String URL_BASE="http://192.168.0.193:8181/tucanalmovil/devices/";
//	public static String URL_BASE="http://192.168.43.200:8181/tucanalmovil/devices/";
	//public static String URL_BASE="https://192.168.43.200:8443/tucanalmovil/devices/";

//	public static String URL_BASE="http://192.168.0.193:8181/tucanalmovil/devices/";
	
	private JavascriptFacade jf;
	
	
	@Override
	public void onResume() {
	  super.onResume();

	  // Register mMessageReceiver to receive messages.
	  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
	      new IntentFilter("refreshChat"));
	}

	// handler for received Intents for the "my-event" event 
	private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
	  @Override
	  public void onReceive(Context context, Intent intent) {
	    // Extract data included in the Intent
	    String message = intent.getStringExtra("message");
	    Log.d("receiver", "Got message: " + message);
	    sendJavascript("refreshChat('" + message + "')");
	  }
	};

	@Override
	protected void onPause() {
	  // Unregister since the activity is not visible
	  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
	  super.onPause();
	} 
	
	
	private FindMeService findMeServ;
	
	
	
	
	
	public FindMeService getFindMeServ() {
		return findMeServ;
	}


	public void setFindMeServ(FindMeService findMeServ) {
		this.findMeServ = findMeServ;
	}


    @Override
    public void onNewIntent(Intent intent){
    	
        Long lastId = intent.getLongExtra(MainActivity.EXTRA_MESSAGE,0L);

    	Log.v(MainActivity.class.getName(), "Intent with lastid " + lastId);

    	
        if(lastId==0) { 
        	sendJavascript("onNotification(false)");
        }
        else {
        	sendJavascript("onNotification(true)");
        }
    }
	
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
        	sendJavascript("onBackKeyDown()");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
	public void onCreate(Bundle savedInstanceState) {
		
		try {
		
			SharedPreferences prefs = getSharedPreferences(
				      "com.ficv.findme", Context.MODE_PRIVATE);
			
			prefs.edit().putString("com.ficv.findme.data", "1default");
			
			
			Log.v(MainActivity.class.getName(), "start");
		
			super.onCreate(savedInstanceState);
			super.init();
			super.clearCache();
			

	        //    super.appView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);


	        
			   LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
			    
			    	
			    if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER )) 
			    { 
			    	buildAlertMessageNoGps();
	//		    Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS );
	//		    startActivity(myIntent);
			    }
			    

			    if(!isNetworkAvailable()) {
			    	buildAlertMessageNoData();
			    }
			       
			
	        jf = new JavascriptFacade(this, appView);
	        appView.addJavascriptInterface(jf, "jf");
	        
	        appView.setWebViewClient(new CordovaWebViewClient(this, appView) {

//	            @Override
//	            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//
//
//
//	                     Log.d("DEBUG", url);
//
//	                     // DO STUFF
//
//	                     return false;
//	  
//	            }
	            
	            @Override
	            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
	                Log.i("WEB_VIEW_TEST", "error code:" + errorCode);
	                view.loadUrl("file:///android_asset/www/retry.html");
	                //super.onReceivedError(view, errorCode, description, failingUrl);
	                //TO DO - do something else in here if the site is down
	                }
	              

	        });
			
	        super.setIntegerProperty("loadUrlTimeoutValue", 60000);
			//super.setIntegerProperty("splashscreen", R.drawable.splash);
//			super.loadUrl("file:///android_asset/www/app.html", 2000);
			super.loadUrl("file:///android_asset/www/index.html");

	       // super.loadUrl("http://findme.cloudfoundry.com/resources/static/www/index.html");

	
			
			//startService(new Intent(GpsService.class.getName()));

			Intent intent = new Intent(this, FindMeService.class);
			PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

			AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
			// Start every 30 seconds
			alarm.setRepeating(AlarmManager.RTC_WAKEUP, (new Date()).getTime(), 30*1000, pintent); 	
			
			doBindService();
			
//			 Toast.makeText(this, "Number of elements" + findMeServ.getWordList().size(),
//			          Toast.LENGTH_SHORT).show();
			
			JavascriptFacade.DATA="30000";
			
		} catch(Throwable t) {
			Log.e("MainActivity", t.getMessage(), t);

		} 
	}
		
	
	public void onResume(Bundle savedInstanceState) {
		
		
//		super.onCreate(savedInstanceState);
//		super.loadUrl("file:///android_asset/www/app.html");
	}
	
	
	private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	
	
	 private  void buildAlertMessageNoGps() {
	        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
//	        builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
	        builder.setMessage("El GPS parece estar deshabilitado, ¿quiere activarlo?")
	               .setCancelable(false)
	               .setPositiveButton("Si", new DialogInterface.OnClickListener() {
	                   public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
	                     startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
	                   }
	               })
	               .setNegativeButton("No", new DialogInterface.OnClickListener() {
	                   public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
	                        dialog.cancel();
	                   }
	               });
	        final AlertDialog alert = builder.create();
	        alert.show();
	    }

	 

	 private  void buildAlertMessageNoData() {
	        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        //builder.setMessage("Your Internet connections seems to be disabled, do you want to enable it? Then restart application.")
	        builder.setMessage("Parece que no tiene buena conexión a internet. ¿Quiere revisar la configuración? Reiniciela después.")
	               .setCancelable(false)
	               .setPositiveButton("Si", new DialogInterface.OnClickListener() {
	                   public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
	                     startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
	                     finish();
	                   }
	               })
	               .setNegativeButton("No", new DialogInterface.OnClickListener() {
	                   public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
	                        //finish();
	                   }
	               });
	        final AlertDialog alert = builder.create();
	        alert.show();
	    }	 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return false;
	}	
	
	


	  private ServiceConnection mConnection = new ServiceConnection() {

	    public void onServiceConnected(ComponentName className, IBinder binder) {
	    	findMeServ = ((FindMeService.MyBinder) binder).getService();
	      Toast.makeText(MainActivity.this, "Connected",
	          Toast.LENGTH_SHORT).show();
	    }

	    public void onServiceDisconnected(ComponentName className) {
	    	findMeServ = null;
	        Toast.makeText(MainActivity.this, "Disconnected",
	                Toast.LENGTH_SHORT).show();
	    }
	  };


	  void doBindService() {
	    bindService(new Intent(this, FindMeService.class), mConnection,
	        Context.BIND_AUTO_CREATE);
	  }
	
	 
} 
